package com.itlong.cloud.controller.current;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.AppTouristDTO;
import com.itlong.cloud.POJO.DTO.app.AppUserRegisterDTO;
import com.itlong.cloud.POJO.PO.AppUserInfoPO;
import com.itlong.cloud.POJO.PO.UserLoginLogPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.AppUserCacheVO;
import com.itlong.cloud.POJO.VO.app.AppUserOwnProjectVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.LanguageTypeEnum;
import com.itlong.cloud.enumerate.SystemTypeEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.enumerate.ecode_en.AppErrorCodeEnumEN;
import com.itlong.cloud.enumerate.ecode_en.BaseErrorCodeEnumEN;
import com.itlong.cloud.iottp.IIotTpJPushClientServiceClient;
import com.itlong.cloud.iottp.IIotTpSmsServiceClient;
import com.itlong.cloud.noncore.commons.IUserLoginLogServiceClient;
import com.itlong.cloud.project.app.IAppProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppRegisterServiceClient;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *     新版APP登录与注册版块控制器
 * </desc>
 *
 * @create  2017/9/19
 */
@RestController
@RequestMapping("/user")
@RefreshScope
public class AppRegisterController extends BaseController{
    private static final Logger LOG = LoggerFactory.getLogger(AppRegisterController.class);

    @Value("${" + PlatformConstants.APP_REQUEST_PARAMS_ENCRYPT_KEY + "}")
    public String APP_REQUEST_PARAMS_ENCRYPT_KEY;

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    public String APP_USER_TOKEN_KEY;

    @Autowired
    IAppRegisterServiceClient iAppRegisterServiceClient;

    @Autowired
    private RedisService<AppUserCacheVO> redisService;

    @Autowired
    IIotTpSmsServiceClient iIotTpSmsServiceClient;

    @Autowired
    IUserLoginLogServiceClient iUserLoginLogServiceClient;

    //极光推送国内
    @Autowired
    IIotTpJPushClientServiceClient iIotTpJPushClientServiceClient;

    @Autowired
    IAppProjectServiceClient iAppProjectServiceClient;



    /**
     * <desc>
     *     APP注册时获取验证码
     * </desc>
     * @param phoneNo 手机号或邮箱
     * @param mode 0代表手机；1代表邮箱
     * @param language 语言
     * @param type 类型：1-注册，2-忘记密码或房屋认证时发送房间业主验证码，3-修改用户手机号，4-验证原手机号
     * @return
     * @author cuiduanwu
     */
    @ResponseBody
    @RequestMapping(path = "/sendMsg",method = RequestMethod.POST)
    public Object appSendSmsCode(String phoneNo,String mode,String type,String createTime,String sign,String language){
        try {
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                phoneNo = request.getAttribute("phoneNo") == null ? null : request.getAttribute("phoneNo").toString();
                mode = request.getAttribute("mode") == null ? null : request.getAttribute("mode").toString();
                type = request.getAttribute("type") == null ? null : request.getAttribute("type").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("phoneNo",phoneNo);
            params.put("mode",mode);
            params.put("type",type);
            params.put("createTime",createTime);
            params.put("language",language);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                }
            } else {
                if (!Md5EncryptUtil.checkAppSignValue(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                }
            }
            if (StringUtils.isEmpty(phoneNo)||StringUtils.isEmpty(mode)||StringUtils.isEmpty(type)||StringUtils.isBlank(createTime)){
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? BaseErrorCodeEnum.NOT_PARAM.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return new MessageVO(errorCode);
            }else {
                String smsCode =  NumberHandlerUtil.randomNum(6);
                boolean sendFlag = false;  //验证码发送标志,true-发送成功，false-发送失败
                String content="";
                AppUserInfoPO appUserInfoPO=null;
                if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){//手机号注册
                   content = "验证码:"+smsCode+",该验证码将在30分钟后失效.";
                    if (!NumberHandlerUtil.isPhoneNo(phoneNo)){ //手机号是否合法
                        return new  MessageVO(AppErrorCodeEnum.PHONE_NOT_MATCH.getErrorCode());
                    }
                    appUserInfoPO = iAppRegisterServiceClient.getUserByPhoneNo(phoneNo);
                }else {
                    content =String.format("%s%s%s","Hello! To ensure that it is your own operation, please enter the verification code in the below mail box,the verification code is ",smsCode,",Do not reveal the verification code to anyone.") ;
                    appUserInfoPO = iAppRegisterServiceClient.getUserByEmail(phoneNo);
                }
                if ("1".equals(type)){
                    if (appUserInfoPO != null&&StringUtils.isNotBlank(appUserInfoPO.getPassword())){//检查手机号码与密码是否已存在
                        ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))?AppErrorCodeEnum.EXIST_PHONENO.getErrorCode(): AppErrorCodeEnumEN.EXIST_EMAIL.getErrorCode();
                        return  new MessageVO(errorCode);
                    }
                }else if("2".equals(type)){//忘记密码或房屋认证时发送房间业主验证码
                    if (appUserInfoPO == null){ //检查手机号码是否已存在
                        ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))?AppErrorCodeEnum.NOT_EXIST_PHONENO.getErrorCode(): AppErrorCodeEnumEN.NOT_EXIST_EMAIL.getErrorCode();
                        return  new MessageVO(errorCode);
                    }
                    //检查手机号码是否已激活
                   if(appUserInfoPO != null&&StringUtils.isBlank(appUserInfoPO.getPassword())){
                       ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))?AppErrorCodeEnum.NOT_EXIST_PHONENO.getErrorCode(): AppErrorCodeEnumEN.NOT_EXIST_EMAIL.getErrorCode();
                       return  new MessageVO(errorCode);
                   }
                }else if("3".equals(type)){//修改用户手机号
                    if (appUserInfoPO != null){ //检查手机号码是否已存在
                        ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))?AppErrorCodeEnum.EXIST_PHONENO.getErrorCode(): AppErrorCodeEnumEN.NOT_EXIST_EMAIL.getErrorCode();
                        return  new MessageVO(errorCode);
                    }
                }else if("4".equals(type)){//修改用户手机号,验证原手机号
                    if(appUserInfoPO == null || StringUtils.isBlank(appUserInfoPO.getPassword())){//检查手机号是否是注册用户
                        ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))?AppErrorCodeEnum.EXIST_PHONENO.getErrorCode(): AppErrorCodeEnumEN.NOT_EXIST_EMAIL.getErrorCode();
                        return  new MessageVO(errorCode);
                    }
                }else if("5".equals(type)){//注销,验证原手机号
                    if(appUserInfoPO == null || StringUtils.isBlank(appUserInfoPO.getPassword())){//检查手机号是否是注册用户
                        ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))?AppErrorCodeEnum.EXIST_PHONENO.getErrorCode(): AppErrorCodeEnumEN.NOT_EXIST_EMAIL.getErrorCode();
                        return  new MessageVO(errorCode);
                    }
                }else {
                    LOG.info("【APP_登录注册模块_获取验证码类型错误】"+type);
                    ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? BaseErrorCodeEnum.NOT_PARAM.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                    return new MessageVO(errorCode);
                }
                //需求10分钟之内可以发送3条
                //按顺序放入缓存3条如果都存在则报错,每条10分钟超时
                int count1 = redisService.get(RedisConstant.REDIS_SMS_TIMES+"1"+phoneNo) == null ? 0 : 1;
                int count2 = redisService.get(RedisConstant.REDIS_SMS_TIMES+"2"+phoneNo) == null ? 0 : 1;
                int count3 = redisService.get(RedisConstant.REDIS_SMS_TIMES+"3"+phoneNo) == null ? 0 : 1;
                if (count1 != 0 && count2 != 0 && count3 != 0) {//都不为空证明已经发了3次
                    ErrorCode errorCode =  (LanguageTypeEnum.CHINESE.getLanguage().equals(language))?AppErrorCodeEnum.SMSCODE_SEND_TO_MORE.getErrorCode(): AppErrorCodeEnumEN.SMSCODE_SEND_TO_MORE.getErrorCode();
                    return  new MessageVO(errorCode);
                }
                if (count1 == 0) {
                    redisService.set(RedisConstant.REDIS_SMS_TIMES+"1"+phoneNo,RedisConstant.SMS_TIMES_TIME,"1");
                } else if (count2 == 0) {
                    redisService.set(RedisConstant.REDIS_SMS_TIMES+"2"+phoneNo,RedisConstant.SMS_TIMES_TIME,"1");
                } else if (count3 == 0) {
                    redisService.set(RedisConstant.REDIS_SMS_TIMES+"3"+phoneNo,RedisConstant.SMS_TIMES_TIME,"1");
                }
                if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){
                    sendFlag = iIotTpSmsServiceClient.sendSmsCodeByPhone(phoneNo,content);
                }else {
                    sendFlag = iIotTpSmsServiceClient.sendSmsCodeByEmail(phoneNo,content);
                }
                if (sendFlag){
                    boolean redisFlag=false;
                    if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){
                       redisFlag = redisService.set(RedisConstant.REDIS_SMS_CODE+phoneNo,RedisConstant.SMS_CODE_TIME,smsCode);
                    }else {
                       redisFlag = redisService.set(RedisConstant.REDIS_EMAIL_CODE+phoneNo,RedisConstant.EMAIL_CODE_TIME,smsCode);
                    }
                    if (redisFlag){
                        ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? BaseErrorCodeEnum.SUCCESS.getErrorCode():BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
                        return new MessageVO(errorCode);
                    }else {
                        LOG.info("【APP_登录注册模块_获取验证码缓存验证码失败】");
                        ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.SMSCODE_SEND_ERR.getErrorCode():AppErrorCodeEnumEN.SMSCODE_SEND_ERR.getErrorCode();
                        return new MessageVO(errorCode);
                    }
                }
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.SMSCODE_SEND_ERR.getErrorCode():AppErrorCodeEnumEN.SMSCODE_SEND_ERR.getErrorCode();
                return new MessageVO(errorCode);

            }
        }catch (Exception e){
            throw new DataAccessException("【APP_登录注册模块_获取验证码】获取验证码失败",e);
        }
    }


    /**
     * <desc>
     *     APP注册时验证验证码是否正确
     * </desc>
     * @param phoneNo 手机号
     * @param language 语言
     * @param smsCode  短信验证码
     * @return
     * @author cuiduanwu
     */
    @ResponseBody
    @RequestMapping(path = "/register",method = RequestMethod.POST)
    public Object appRegister(String phoneNo,String smsCode,String createTime,String sign,String language) throws  Exception{
        try {
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                phoneNo = request.getAttribute("phoneNo") == null ? null : request.getAttribute("phoneNo").toString();
                smsCode = request.getAttribute("smsCode") == null ? null : request.getAttribute("smsCode").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("phoneNo",phoneNo);
            params.put("smsCode",smsCode);
            params.put("createTime",createTime);
            params.put("language",language);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                 }
            } else {
                if (!Md5EncryptUtil.checkAppSignValue(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                }
            }
            //校空
            if (StringUtils.isBlank(phoneNo)||StringUtils.isBlank(smsCode)||StringUtils.isBlank(createTime)){
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? BaseErrorCodeEnum.NOT_PARAM.getErrorCode():BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return new MessageVO(errorCode);
            }else if ((LanguageTypeEnum.CHINESE.getLanguage().equals(language))&&(!NumberHandlerUtil.isPhoneNo(phoneNo))){
                return new MessageVO(AppErrorCodeEnum.PHONE_NOT_MATCH.getErrorCode());
            }else if((LanguageTypeEnum.ENGLISH.getLanguage().equals(language))&&(!StringHandlerUtil.isEmail(phoneNo))){
                return new MessageVO(AppErrorCodeEnumEN.EMAIL_FORMAT_ERROR.getErrorCode());
            }
            String smsCodeCache ="";
            if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){
                smsCodeCache = redisService.get(RedisConstant.REDIS_SMS_CODE+phoneNo);
            }else {
                smsCodeCache = redisService.get(RedisConstant.REDIS_EMAIL_CODE+phoneNo);
            }
            if (StringUtils.isBlank(smsCodeCache)){
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.SMSCODE_EXPIRE.getErrorCode():AppErrorCodeEnumEN.SMSCODE_EXPIRE.getErrorCode();
                return new MessageVO(errorCode);
            }else if (StringUtils.isNotBlank(smsCodeCache)&&!smsCodeCache.equals(smsCode)){
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.SMSCODE_ERR.getErrorCode():AppErrorCodeEnumEN.SMSCODE_ERR.getErrorCode();
                return new MessageVO(errorCode);
            }else if (StringUtils.isNotBlank(smsCodeCache)&&smsCodeCache.equals(smsCode)){
                String userId = LogicIdUtil.userBusinessId();
                AppUserInfoPO appUserInfoPO=null;
               if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){
                appUserInfoPO = iAppRegisterServiceClient.getUserByPhoneNo(phoneNo); //预授权未注册激活
               }else {
                   appUserInfoPO = iAppRegisterServiceClient.getUserByEmail(phoneNo); //预授权未注册激活
               }
                if (appUserInfoPO != null){
                    userId = appUserInfoPO.getUserId();
                }
                String token = UserTokenUtil.tokenEncrypt(userId,APP_USER_TOKEN_KEY, SystemTypeEnum.IOS.getType());
                AppUserCacheVO appUserCacheVO = new AppUserCacheVO(userId,phoneNo,token);
                boolean flag = redisService.set(RedisConstant.APP_LOGIN+userId,RedisConstant.APP_USER_CHECK_SMSCODE_TOKEN_TIME,appUserCacheVO);
                if (flag) {
                    JSONObject js = new JSONObject();
                    js.put("token",token);
                    System.out.println("用户ID:"+userId+"----"+token);
                    redisService.del(RedisConstant.REDIS_SMS_CODE+phoneNo); //业务成功后移除验证码缓存
                    ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? BaseErrorCodeEnum.SUCCESS.getErrorCode():BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
                    return  new MessageVO(errorCode,js);
                }else {
                    LOG.info("【APP_登录注册模块_验证码验证_缓存用户】redis保存用户token失败");
                    throw new DataAccessException("【APP_登录注册模块_验证码验证_缓存用户】缓存用户失败");
                }
            }else {
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? BaseErrorCodeEnum.ERROR.getErrorCode():BaseErrorCodeEnumEN.ERROR.getErrorCode();
                return  new MessageVO(errorCode);
            }
        }catch (Exception e){
            LOG.error("【APP_登录注册模块_验证码验证异常】",e);
            throw new DataAccessException("【APP_登录注册模块_验证码验证异常】验证码验证异常",e);
        }
    }


    /**
     * <desc>
     *     APP2.0找回密码时验证验证码是否正确
     * </desc>
     * @param phoneNo 手机号
     * @param language 语言
     * @param smsCode  短信验证码
     * @return
     * @author Qiang.S
     * @createDate 2019-06-28
     *
     */
    @ResponseBody
    @UnAuthAccessRequired
    @RequestMapping(path = "/checkSmsForChangePhone",method = RequestMethod.POST)
    public Object checkSmsForChangePhone(String phoneNo,String smsCode,String createTime,String sign,String language) throws  Exception{
        try {
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                phoneNo = request.getAttribute("phoneNo") == null ? null : request.getAttribute("phoneNo").toString();
                smsCode = request.getAttribute("smsCode") == null ? null : request.getAttribute("smsCode").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("phoneNo",phoneNo);
            params.put("smsCode",smsCode);
            params.put("createTime",createTime);
            params.put("language",language);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                }
            } else {
                if (!Md5EncryptUtil.checkAppSignValue(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                }
            }
            //校空
            if (StringUtils.isBlank(phoneNo)||StringUtils.isBlank(smsCode)||StringUtils.isBlank(createTime)){
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? BaseErrorCodeEnum.NOT_PARAM.getErrorCode():BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return new MessageVO(errorCode);
            }else if ((LanguageTypeEnum.CHINESE.getLanguage().equals(language))&&(!NumberHandlerUtil.isPhoneNo(phoneNo))){
                return new MessageVO(AppErrorCodeEnum.PHONE_NOT_MATCH.getErrorCode());
            }else if((LanguageTypeEnum.ENGLISH.getLanguage().equals(language))&&(!StringHandlerUtil.isEmail(phoneNo))){
                return new MessageVO(AppErrorCodeEnumEN.EMAIL_FORMAT_ERROR.getErrorCode());
            }
            String smsCodeCache ="";
            if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){
                smsCodeCache = redisService.get(RedisConstant.REDIS_SMS_CODE+phoneNo);
            }else {
                smsCodeCache = redisService.get(RedisConstant.REDIS_EMAIL_CODE+phoneNo);
            }
            if (StringUtils.isBlank(smsCodeCache)){
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.SMSCODE_EXPIRE.getErrorCode():AppErrorCodeEnumEN.SMSCODE_EXPIRE.getErrorCode();
                return new MessageVO(errorCode);
            }else if (StringUtils.isNotBlank(smsCodeCache)&&!smsCodeCache.equals(smsCode)){
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? AppErrorCodeEnum.SMSCODE_ERR.getErrorCode():AppErrorCodeEnumEN.SMSCODE_ERR.getErrorCode();
                return new MessageVO(errorCode);
            }else if (StringUtils.isNotBlank(smsCodeCache)&&smsCodeCache.equals(smsCode)){
//                    redisService.del(RedisConstant.REDIS_SMS_CODE+phoneNo); //业务成功后移除验证码缓存
                    ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? BaseErrorCodeEnum.SUCCESS.getErrorCode():BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
                    return  new MessageVO(errorCode);
            }else {
                ErrorCode errorCode = (LanguageTypeEnum.CHINESE.getLanguage().equals(language))? BaseErrorCodeEnum.ERROR.getErrorCode():BaseErrorCodeEnumEN.ERROR.getErrorCode();
                return  new MessageVO(errorCode);
            }
        }catch (Exception e){
            LOG.error("【APP_登录注册模块_验证码验证异常】",e);
            throw new DataAccessException("【APP_登录注册模块_验证码验证异常】验证码验证异常",e);
        }
    }

    /**
     * <desc>
     *     APP端用户注册提交
     * </desc>
     *
     * @param token
     * @param nickName  用户昵称
     * @param userName  用户姓名
     * @param sex 性别，0男、1女
     * @param pswd  密码
     * @param language  语言
     * @return
     * @author cuiduanwu
     * @throws Exception
     */
    @RequestMapping(path = "/registerProjectInfo",method = RequestMethod.POST)
    @ResponseBody
    public Object appRegisterProjectInfo(String token,String nickName,String userName,String sex,String pswd,String createTime,String sign,String language, String uuid) throws  Exception {
        try {
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
                nickName = request.getAttribute("nickName") == null ? null : request.getAttribute("nickName").toString();
                userName = request.getAttribute("userName") == null ? null : request.getAttribute("userName").toString();
                sex = request.getAttribute("sex") == null ? null : request.getAttribute("sex").toString();
                pswd = request.getAttribute("pswd") == null ? null : request.getAttribute("pswd").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
                uuid = request.getAttribute("uuid") == null ? null : request.getAttribute("uuid").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            if (sex != null && nickName != null) {
                params.put("sex",sex);
                params.put("nickName",nickName);
            }
            params.put("userName",userName);
            params.put("pswd",pswd);
            params.put("createTime",createTime);
            params.put("language",language);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            } else {
                params.put("uuid",uuid);
                if (!Md5EncryptUtil.checkAppSignValue(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            }
            String pwd = pswd;
            pswd = UserTokenUtil.getPassword(pswd, APP_USER_TOKEN_KEY);
            //如果解密失败不做处理，此try catch主要做兼容旧版本app用户密码与后台交互并没有做des加密
            if(pswd == null) {
                pswd = pwd;
            }
            //校空
            if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)&&StringUtils.isBlank(userName)){
                return  new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //校空
            if(!LanguageTypeEnum.CHINESE.getLanguage().equals(language)&&StringUtils.isBlank(sex)){
                return  new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(userName)||StringUtils.isBlank(pswd)||StringUtils.isBlank(createTime)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode():BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return  new MessageVO(errorCode);
            }
            if (StringUtils.isBlank(pswd)||pswd.length()<6||pswd.length()>16){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.PSWD_LENGTH_ERROR.getErrorCode():AppErrorCodeEnumEN.PSWD_LENGTH_ERROR.getErrorCode();
                return  new MessageVO(errorCode);
            }
            String userId = UserTokenUtil.newAPPTokenDecrypt(token,APP_USER_TOKEN_KEY);
            if (StringUtils.isNotEmpty(userId)) {
                AppUserRegisterDTO appUserRegisterDTO = new AppUserRegisterDTO(userId, userName, nickName, sex, Md5EncryptUtil.md5(pswd), token);
                appUserRegisterDTO.setLanguage(language);
                appUserRegisterDTO.setUuid(uuid);
                boolean flag = iAppRegisterServiceClient.registerUser(appUserRegisterDTO);
                if (flag) {
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.SUCCESS.getErrorCode():BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
                    return  new MessageVO(errorCode);
                } else {
                    LOG.info("【APP_注册与登录_注册提交】保存或更新用户信息失败");
//                    throw new DataAccessException("【APP_注册与登录_注册提交_保存或更新用户信息】保存或更新用户信息失败");
                }
            }
            ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.ERROR.getErrorCode():BaseErrorCodeEnumEN.ERROR.getErrorCode();
            return  new MessageVO(errorCode);
        } catch (Exception e) {
            LOG.error("【APP_注册与登录_注册提交】保存或更新用户信息失败",e);
            throw new DataAccessException("【APP_注册与登录_注册提交_保存或更新用户信息】保存或更新用户信息失败",e);
        }
    }

    /**
     * <desc>
     *     APP端更新用户密码
     * </desc>
     *
     * @param phoneNo 手机号或邮箱
     * @param pswd   新密码
     * @param smsCode  验证码
     * @return
     * @author cuiduanwu
     * @throws Exception
     */
    @LoggerInfo(operateDesc = LogDescConstant.APP_UPDATE_PSWD)
    @RequestMapping(path = "/retrievePswd",method = RequestMethod.POST)
    @ResponseBody
    public Object appRetrievePswd(String phoneNo,String pswd,String smsCode,String createTime,String sign,String language) throws Exception{
        try {
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                phoneNo = request.getAttribute("phoneNo") == null ? null : request.getAttribute("phoneNo").toString();
                pswd = request.getAttribute("pswd") == null ? null : request.getAttribute("pswd").toString();
                smsCode = request.getAttribute("smsCode") == null ? null : request.getAttribute("smsCode").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("phoneNo",phoneNo);
            params.put("pswd",pswd);
            params.put("smsCode",smsCode);
            params.put("createTime",createTime);
            params.put("language",language);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params, sign, APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            } else {
                if (!Md5EncryptUtil.checkAppSignValue(params, sign, APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode():AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            }
            String pwd = pswd;
            pswd = UserTokenUtil.getPassword(pswd, APP_USER_TOKEN_KEY);
            //如果解密失败不做处理，此try catch主要做兼容旧版本app用户密码与后台交互并没有做des加密
            if(pswd == null) {
                pswd = pwd;
            }
            if (StringUtils.isBlank(phoneNo)||StringUtils.isBlank(pswd)||StringUtils.isBlank(smsCode)||StringUtils.isBlank(createTime)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.PARAM_ERR.getErrorCode():BaseErrorCodeEnumEN.PARAM_ERR.getErrorCode();
                return  new MessageVO(errorCode);
            }else if ((LanguageTypeEnum.CHINESE.getLanguage().equals(language))&&(!NumberHandlerUtil.isPhoneNo(phoneNo))){
                return new MessageVO(AppErrorCodeEnum.PHONE_NOT_MATCH.getErrorCode());
            }else if((LanguageTypeEnum.ENGLISH.getLanguage().equals(language))&&(!StringHandlerUtil.isEmail(phoneNo))){
                return new MessageVO(AppErrorCodeEnumEN.EMAIL_FORMAT_ERROR.getErrorCode());
            }else if (StringUtils.isBlank(pswd)||pswd.length()<6||pswd.length()>16){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.PSWD_LENGTH_ERROR.getErrorCode():AppErrorCodeEnumEN.PSWD_LENGTH_ERROR.getErrorCode();
                return  new MessageVO(errorCode);
            }
            boolean flag = false;
            String smsCodeCache = null,mode = "0";
            if (NumberHandlerUtil.isPhoneNo(phoneNo)){  //手机号
                smsCodeCache = redisService.get(RedisConstant.REDIS_SMS_CODE+phoneNo);
            }else if(StringHandlerUtil.isEmail(phoneNo)){  //邮箱
                smsCodeCache = redisService.get(RedisConstant.REDIS_EMAIL_CODE+phoneNo);
                mode = "1";
            }else {
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode():BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return  new MessageVO(errorCode);
            }
            if (StringUtils.isBlank(smsCodeCache)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.SMSCODE_EXPIRE.getErrorCode():AppErrorCodeEnumEN.SMSCODE_EXPIRE.getErrorCode();
                return  new MessageVO(errorCode);
            }else if (StringUtils.isNotBlank(smsCodeCache)&&!smsCodeCache.equals(smsCode)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.SMSCODE_ERR.getErrorCode():AppErrorCodeEnumEN.SMSCODE_ERR.getErrorCode();
                return  new MessageVO(errorCode);
            }else if (StringUtils.isNotBlank(smsCodeCache)&&smsCodeCache.equals(smsCode)){
                boolean result = iAppRegisterServiceClient.updateUserPswd(phoneNo,Md5EncryptUtil.md5(pswd),mode);
                if (result){
                    if ("0".equals(mode)){ //手机号
                        redisService.del(RedisConstant.REDIS_SMS_CODE+phoneNo);//业务成功后移除验证码缓存
                    }else { //邮箱
                        redisService.del(RedisConstant.REDIS_EMAIL_CODE+phoneNo);//业务成功后移除验证码缓存
                    }
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.SUCCESS.getErrorCode():BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
                    return  new MessageVO(errorCode);
                }else {
                    throw new DataAccessException("【APP_登录注册模块_找回密码】找回密码失败");
                }
            }
            ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.SMSCODE_ERR.getErrorCode():AppErrorCodeEnumEN.SMSCODE_ERR.getErrorCode();
            return  new MessageVO(errorCode);
        }catch (Exception e){
            LOG.error("【APP_登录注册模块_找回密码】找回密码失败",e);
            throw new DataAccessException("【APP_登录注册模块_找回密码】找回密码失败");
        }
    }


    /**
     * <desc>
     *     APP端用户登录
     * </desc>
     *
     * @param phoneNo  手机号
     * @param pswd  密码
     * @return
     */
    @LoggerInfo(identifer = "login")
    @RequestMapping(path = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Object appUserLogin(String phoneNo,String pswd,String loginDevice,String createTime,String sign,String uuid,String language,HttpServletRequest request){
        MessageVO messageVO;
        try {
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                phoneNo = request.getAttribute("phoneNo") == null ? null : request.getAttribute("phoneNo").toString();
                pswd = request.getAttribute("pswd") == null ? null : request.getAttribute("pswd").toString();
                loginDevice = request.getAttribute("loginDevice") == null ? null : request.getAttribute("loginDevice").toString();
                uuid = request.getAttribute("uuid") == null ? null : request.getAttribute("uuid").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("phoneNo",phoneNo);
            params.put("pswd",pswd);
            params.put("createTime",createTime);
            params.put("loginDevice",loginDevice);
            params.put("uuid",uuid);
            params.put("language",language);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            } else {
                if (!Md5EncryptUtil.checkAppSignValue(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            }
            //登录前，先检查账号有没有被锁定
            MessageVO checkLockMessage = iAppRegisterServiceClient.getAppAccountLockDetail(phoneNo);
            if (checkLockMessage != null) {
                request.setAttribute("checkMessage",checkLockMessage);
                return checkLockMessage;
            }

            String pwd = pswd;
            pswd = UserTokenUtil.getPassword(pswd, APP_USER_TOKEN_KEY);
            //如果解密失败不做处理，此try catch主要做兼容旧版本app用户密码与后台交互并没有做des加密
            if(pswd == null) {
                pswd = pwd;
            }
            if (StringUtils.isBlank(phoneNo)||StringUtils.isBlank(pswd)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.PHONE_PSWD_EMPTY.getErrorCode():AppErrorCodeEnumEN.PHONE_PSWD_EMPTY.getErrorCode();
                return  new MessageVO(errorCode);
            }else if ((LanguageTypeEnum.CHINESE.getLanguage().equals(language))&&(!NumberHandlerUtil.isPhoneNo(phoneNo))){
                return new MessageVO(AppErrorCodeEnum.PHONE_NOT_MATCH.getErrorCode());
            }else if((LanguageTypeEnum.ENGLISH.getLanguage().equals(language))&&(!StringHandlerUtil.isEmail(phoneNo))){
                return new MessageVO(AppErrorCodeEnumEN.EMAIL_FORMAT_ERROR.getErrorCode());
            }else if (pswd.length()<6||pswd.length()>16){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.PSWD_LENGTH_ERROR.getErrorCode():AppErrorCodeEnumEN.PSWD_LENGTH_ERROR.getErrorCode();
                return  new MessageVO(errorCode);
            }else if (StringUtils.isBlank(createTime)||StringUtils.isBlank(loginDevice)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode():BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return  new MessageVO(errorCode);
            }
            UserLoginLogPO userLoginLogPO = new UserLoginLogPO(phoneNo,null, HttpProtocolUtil.getIpAddr(request));
            if ("1".equals(loginDevice)){ //安卓
                userLoginLogPO.setSystemType(3);
            }else { //苹果
                userLoginLogPO.setSystemType(4);
            }
            boolean isExistLogin = false;
            AppUserInfoPO appUserInfoPO = null;
            AppUserCacheVO oldCacheUserVO = null;
            if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){  //手机
                appUserInfoPO = iAppRegisterServiceClient.getUserByPhoneNo(phoneNo);
            }else {
                appUserInfoPO = iAppRegisterServiceClient.getUserByEmail(phoneNo);
            }
            if (appUserInfoPO != null){
                if (StringUtils.isBlank(appUserInfoPO.getPassword())){ //用户存在，但密码不存在（一卡通或者物业后台预授权或邀请家人获取权限）
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.USER_PHONE_IS_NOT_EXIST.getErrorCode():AppErrorCodeEnumEN.USER_NOT_EXIST.getErrorCode();
                    return new MessageVO(errorCode);
                }
//                LOG.info("【APP_登录注册模块_重新登录】手机号:"+phoneNo+"--登录终端:"+loginDevice+"--IP:"+userLoginLogPO.getIp()+"--登录UUID:"+uuid);
                oldCacheUserVO = redisService.getObject(RedisConstant.APP_LOGIN+appUserInfoPO.getUserId(),AppUserCacheVO.class);
                if (oldCacheUserVO != null&&StringUtils.isNotBlank(oldCacheUserVO.getUuid())&&!uuid.equals(oldCacheUserVO.getUuid())){ //缓存存在，缓存中UUID与请求的UUID不一致
//                    LOG.info("【APP_登录注册模块_用户旧缓存存在】手机号:"+phoneNo+"--登录终端:"+loginDevice+"--IP:"+userLoginLogPO.getIp()+"--旧UUID:"+oldCacheUserVO.getUuid()+"--新UUID:"+uuid);
                    isExistLogin = true;
                }
            }else {
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.USER_PHONE_IS_NOT_EXIST.getErrorCode():AppErrorCodeEnumEN.NOT_EXIST_EMAIL.getErrorCode();
                return new MessageVO(errorCode);
            }
            if (StringUtils.isBlank(appUserInfoPO.getToken())){
                String token = UserTokenUtil.tokenEncrypt(appUserInfoPO.getUserId(),APP_USER_TOKEN_KEY, SystemTypeEnum.IOS.getType());
                appUserInfoPO.setToken(token);
            }
            AppUserCacheVO appUserCacheVO = null;
            if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){  //手机
                appUserCacheVO = iAppRegisterServiceClient.appUserLogin(phoneNo,Md5EncryptUtil.md5(pswd),loginDevice);
            }else {
                appUserCacheVO = iAppRegisterServiceClient.appUserLoginByEmail(phoneNo,Md5EncryptUtil.md5(pswd),loginDevice);
            }
            if (appUserCacheVO != null){
                appUserCacheVO.setToken(appUserInfoPO.getToken());
                if (1!=appUserCacheVO.getStatus()){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.USER_ACCOUNT_REFUSE.getErrorCode():AppErrorCodeEnumEN.USER_ACCOUNT_REFUSE.getErrorCode();
                    messageVO =  new MessageVO(errorCode);
                    //登录日志
                    userLoginLogPO.setDescription("登录"+errorCode.getCodeMsg());
//                    iUserLoginLogServiceClient.saveBuild(userLoginLogPO);
                }else {
                    List<AppUserOwnProjectVO> userOwnProjectList = iAppRegisterServiceClient.getUserOwnProjectsInfo(appUserCacheVO.getUserId(),loginDevice);
                    if (userOwnProjectList != null&&userOwnProjectList.size()>0){ //未申请房屋认证审核通过或者全部房间均被迁出
                        if (StringUtils.isBlank(appUserCacheVO.getCurrentProjectId())||StringUtils.isBlank(appUserCacheVO.getCurrentProjectName())){
                            appUserCacheVO.setCurrentProjectId(userOwnProjectList.get(0).getProjectId());
                            appUserCacheVO.setCurrentProjectName(userOwnProjectList.get(0).getProjectName());
                        }
                    }else {
                        appUserCacheVO.setCurrentProjectId("");
                        appUserCacheVO.setCurrentProjectName("");
                    }
                    appUserCacheVO.setProjects(userOwnProjectList);
                    appUserCacheVO.setUuid(uuid);
                    //根据userId和projectId查询该用户是否欠费
                    if(iAppRegisterServiceClient.getUserIsForbidden(appUserCacheVO.getCurrentProjectId(),appUserCacheVO.getUserId())>0){
                        appUserCacheVO.setForbidden("1");
                    }else{
                        appUserCacheVO.setForbidden("0");
                    }
                    // 获取用户项目信息状态（目前只有缴费通知）、欠费房间id
                    AppUserCacheVO appUserCacheSimple = iAppRegisterServiceClient.getUserMsgAndRoomId(appUserCacheVO.getCurrentProjectId(), appUserCacheVO.getUserId(), null);
                    appUserCacheVO.setHasNewMsg(appUserCacheSimple.getHasNewMsg());
                    appUserCacheVO.setRoomId(appUserCacheSimple.getRoomId());
                    boolean redisflag = iAppRegisterServiceClient.loginCacheUserVO(appUserCacheVO);
                    if (redisflag){
                        appUserCacheVO = (AppUserCacheVO)StringHandlerUtil.formatString(appUserCacheVO);
                        userLoginLogPO.setRealName(appUserCacheVO.getUserName());
                        userLoginLogPO.setDescription("登录" + BaseErrorCodeEnum.SUCCESS.getErrorCode().getCodeMsg());
//                        iUserLoginLogServiceClient.saveBuild(userLoginLogPO);

                        if (isExistLogin && oldCacheUserVO != null){
                            boolean pushresult=iIotTpJPushClientServiceClient.pushWithTaskLogin(phoneNo,oldCacheUserVO.getUuid(),
                                    LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.USER_REMIND_REPEAT_LOGIN.getErrorCode().getCodeMsg():AppErrorCodeEnumEN.USER_REMIND_REPEAT_LOGIN.getCodeMsg());
                            if (!pushresult){
                                LOG.info("【APP_登录注册模块_重复登录后极光推送消息失败】");
                            }
                        }
                        ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.SUCCESS.getErrorCode():BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
                        messageVO = new MessageVO(errorCode,appUserCacheVO);
                    }else {
                        LOG.info("【APP_登录注册模块_登录缓存用户失败】");
                        throw new DataAccessException("【APP_登录注册模块_登录缓存用户】登录失败");
                    }
                }
            }else {
                userLoginLogPO.setDescription("登录"+AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode().getCodeMsg());
//                iUserLoginLogServiceClient.saveBuild(userLoginLogPO);
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode():AppErrorCodeEnumEN.USER_NOT_EXIST.getErrorCode();
                messageVO = new MessageVO(errorCode);

                //账号或密码错误，累计5次
                messageVO = iAppRegisterServiceClient.loginErrorHandler(phoneNo,language);
                request.setAttribute("checkMessage",messageVO.getMsg());
                return messageVO;
            }
            request.setAttribute("loginUser",userLoginLogPO);
        }catch (Exception e){
            throw new DataAccessException("【APP_登录注册模块_登录缓存用户】登录失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *     APP2.0用户登录
     * </desc>
     *
     * @param phoneNo  手机号
     * @param pswd  密码
     * @return
     */
    @LoggerInfo(identifer = "newLogin")
    @UnAuthAccessRequired
    @RequestMapping(path = "/newLogin",method = RequestMethod.POST)
    @ResponseBody
    public Object newAppUserLogin(String phoneNo,String pswd,String loginDevice,String createTime,String sign,String uuid,
                                  String language,HttpServletRequest request,String version,String latitude, String longitude){
        MessageVO messageVO;
        try {
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                phoneNo = request.getAttribute("phoneNo") == null ? null : request.getAttribute("phoneNo").toString();
                pswd = request.getAttribute("pswd") == null ? null : request.getAttribute("pswd").toString();
                loginDevice = request.getAttribute("loginDevice") == null ? null : request.getAttribute("loginDevice").toString();
                uuid = request.getAttribute("uuid") == null ? null : request.getAttribute("uuid").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
                version = request.getAttribute("version") == null ? null : request.getAttribute("version").toString();
                latitude = request.getAttribute("latitude") == null ? null : request.getAttribute("latitude").toString();
                longitude = request.getAttribute("longitude") == null ? null : request.getAttribute("longitude").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("phoneNo",phoneNo);
            params.put("pswd",pswd);
            params.put("createTime",createTime);
            params.put("loginDevice",loginDevice);
            params.put("uuid",uuid);
            params.put("language",language);
            params.put("latitude", latitude);
            params.put("longitude", longitude);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            } else {
                params.put("version",version);
                if (!Md5EncryptUtil.checkAppSignValue(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            }

            //登录前，先检查账号有没有被锁定
            MessageVO checkLockMessage = iAppRegisterServiceClient.getAppAccountLockDetail(phoneNo);
            if (checkLockMessage != null) {
                request.setAttribute("checkMessage",checkLockMessage);
                return checkLockMessage;
            }

            String pwd = pswd;
            pswd = UserTokenUtil.getPassword(pswd, APP_USER_TOKEN_KEY);
            //如果解密失败不做处理，此try catch主要做兼容旧版本app用户密码与后台交互并没有做des加密
            if(pswd == null) {
                pswd = pwd;
            }
            if (StringUtils.isBlank(phoneNo)||StringUtils.isBlank(pswd)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.PHONE_PSWD_EMPTY.getErrorCode():AppErrorCodeEnumEN.PHONE_PSWD_EMPTY.getErrorCode();
                return  new MessageVO(errorCode);
            }else if ((LanguageTypeEnum.CHINESE.getLanguage().equals(language))&&(!NumberHandlerUtil.isPhoneNo(phoneNo))){
                return new MessageVO(AppErrorCodeEnum.PHONE_NOT_MATCH.getErrorCode());
            }else if((LanguageTypeEnum.ENGLISH.getLanguage().equals(language))&&(!StringHandlerUtil.isEmail(phoneNo))){
                return new MessageVO(AppErrorCodeEnumEN.EMAIL_FORMAT_ERROR.getErrorCode());
            }else if (pswd.length()<6||pswd.length()>16){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.PSWD_LENGTH_ERROR.getErrorCode():AppErrorCodeEnumEN.PSWD_LENGTH_ERROR.getErrorCode();
                return  new MessageVO(errorCode);
            }else if (StringUtils.isBlank(createTime)||StringUtils.isBlank(loginDevice)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode():BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return  new MessageVO(errorCode);
            }
            UserLoginLogPO userLoginLogPO = new UserLoginLogPO(phoneNo,null, HttpProtocolUtil.getIpAddr(request));
            if ("1".equals(loginDevice)){ //安卓
                userLoginLogPO.setSystemType(3);
            }else { //苹果
                userLoginLogPO.setSystemType(4);
            }
            boolean isExistLogin = false;
            AppUserInfoPO appUserInfoPO;
            AppUserCacheVO oldCacheUserVO;
            Map<String, String> map = new HashMap<>();
            if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){  //手机
                appUserInfoPO = iAppRegisterServiceClient.getUserByPhoneNo(phoneNo);
            }else {
                appUserInfoPO = iAppRegisterServiceClient.getUserByEmail(phoneNo);
            }
            if (appUserInfoPO != null){
                if (StringUtils.isBlank(appUserInfoPO.getPassword())){ //用户存在，但密码不存在（一卡通或者物业后台预授权或邀请家人获取权限）
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.USER_PHONE_IS_NOT_EXIST.getErrorCode():AppErrorCodeEnumEN.USER_NOT_EXIST.getErrorCode();
                    return new MessageVO(errorCode);
                }
                oldCacheUserVO = redisService.getObject(RedisConstant.APP_LOGIN+appUserInfoPO.getUserId(),AppUserCacheVO.class);
                if (oldCacheUserVO != null&&StringUtils.isNotBlank(oldCacheUserVO.getUuid())&&!uuid.equals(oldCacheUserVO.getUuid())){ //缓存存在，缓存中UUID与请求的UUID不一致
                    isExistLogin = true;
                }
                map.put("phoneNo", phoneNo);
            }else {
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language) ? AppErrorCodeEnum.USER_PHONE_IS_NOT_EXIST.getErrorCode() : AppErrorCodeEnumEN.NOT_EXIST_EMAIL.getErrorCode();
                return new MessageVO(errorCode);
            }
            SimpleDateFormat df = new SimpleDateFormat("MMddHHmmss");
            String time = df.format(new Date());
            String token = UserTokenUtil.tokenEncrypt(appUserInfoPO.getUserId() + time, APP_USER_TOKEN_KEY, SystemTypeEnum.IOS.getType());
            appUserInfoPO.setToken(token);
            map.put("token", appUserInfoPO.getToken());
            AppUserCacheVO appUserCacheVO = iAppRegisterServiceClient.appUserLogin(phoneNo, Md5EncryptUtil.md5(pswd), loginDevice);
            if (appUserCacheVO != null) {
                appUserCacheVO.setToken(appUserInfoPO.getToken());
                if (1 != appUserCacheVO.getStatus()) {
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language) ? AppErrorCodeEnum.USER_ACCOUNT_REFUSE.getErrorCode() : AppErrorCodeEnumEN.USER_ACCOUNT_REFUSE.getErrorCode();
                    messageVO = new MessageVO(errorCode);
                    //登录日志
                    userLoginLogPO.setDescription("登录"+errorCode.getCodeMsg());
                }else {
                    List<AppUserOwnProjectVO> userOwnProjectList = iAppRegisterServiceClient.getUserOwnProjectsInfo(appUserCacheVO.getUserId(),loginDevice);
                    if (userOwnProjectList != null&&userOwnProjectList.size()>0){ //未申请房屋认证审核通过或者全部房间均被迁出
                        if (StringUtils.isBlank(appUserCacheVO.getCurrentProjectId())||StringUtils.isBlank(appUserCacheVO.getCurrentProjectName())){
                            appUserCacheVO.setCurrentProjectId(userOwnProjectList.get(0).getProjectId());
                            appUserCacheVO.setCurrentProjectName(userOwnProjectList.get(0).getProjectName());
                        }
                    }else {
                        if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)){
                            //根据定位获取最近的游客项目
                            AppTouristDTO appTouristDTO = new AppTouristDTO();
                            appTouristDTO.setPosition(longitude + "," + latitude);
                            Map<String, Object> touristProject = iAppProjectServiceClient.getProjectByLocation(appTouristDTO);
                            if (touristProject != null && touristProject.get("projectId") != null && touristProject.get("projectName") != null){
                                appUserCacheVO.setCurrentProjectId(touristProject.get("projectId").toString());
                                appUserCacheVO.setCurrentProjectName(touristProject.get("projectName").toString());
                            }else {
                                appUserCacheVO.setCurrentProjectId("");
                                appUserCacheVO.setCurrentProjectName("");
                            }
                        }else {
                            appUserCacheVO.setCurrentProjectId("");
                            appUserCacheVO.setCurrentProjectName("");
                        }

                    }
                    map.put("currentProjectId",appUserCacheVO.getCurrentProjectId());
                    map.put("currentProjectName",appUserCacheVO.getCurrentProjectName());
                    appUserCacheVO.setProjects(userOwnProjectList);
                    appUserCacheVO.setUuid(uuid);
                    //根据userId和projectId查询该用户是否欠费
                    if(iAppRegisterServiceClient.getUserIsForbidden(appUserCacheVO.getCurrentProjectId(),appUserCacheVO.getUserId())>0){
                        appUserCacheVO.setForbidden("1");
                    }else{
                        appUserCacheVO.setForbidden("0");
                    }
                    // 获取用户项目信息状态（目前只有缴费通知）、欠费房间id
                    AppUserCacheVO appUserCacheSimple = iAppRegisterServiceClient.getUserMsgAndRoomId(appUserCacheVO.getCurrentProjectId(), appUserCacheVO.getUserId(), version);
                    appUserCacheVO.setHasNewMsg(appUserCacheSimple.getHasNewMsg());
                    appUserCacheVO.setRoomId(appUserCacheSimple.getRoomId());
                    boolean redisflag = iAppRegisterServiceClient.loginCacheUserVO(appUserCacheVO);
                    if (redisflag){
                        appUserCacheVO = (AppUserCacheVO)StringHandlerUtil.formatString(appUserCacheVO);
                        userLoginLogPO.setRealName(appUserCacheVO.getUserName());
                        userLoginLogPO.setDescription("登录" + BaseErrorCodeEnum.SUCCESS.getErrorCode().getCodeMsg());
//                        iUserLoginLogServiceClient.saveBuild(userLoginLogPO);

                        if (isExistLogin && oldCacheUserVO != null){
                            boolean pushresult=iIotTpJPushClientServiceClient.pushWithTaskLogin(phoneNo,oldCacheUserVO.getUuid(),
                                    LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.USER_REMIND_REPEAT_LOGIN.getErrorCode().getCodeMsg():AppErrorCodeEnumEN.USER_REMIND_REPEAT_LOGIN.getCodeMsg());
                            if (!pushresult){
                                LOG.info("【APP_登录注册模块_重复登录后极光推送消息失败】");
                            }
                        }
                        ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.SUCCESS.getErrorCode():BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
                        messageVO = new MessageVO(errorCode,map);//app2.0
                    }else {
                        LOG.info("【APP_登录注册模块_登录缓存用户失败】");
                        throw new DataAccessException("【APP_登录注册模块_登录缓存用户】登录失败");
                    }
                }
            }else {
                userLoginLogPO.setDescription("登录"+AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode().getCodeMsg());
//                iUserLoginLogServiceClient.saveBuild(userLoginLogPO);
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode():AppErrorCodeEnumEN.USER_NOT_EXIST.getErrorCode();
                messageVO = new MessageVO(errorCode);

                //账号或密码错误，累计5次
                messageVO = iAppRegisterServiceClient.loginErrorHandler(phoneNo,language);
                request.setAttribute("checkMessage",messageVO.getMsg());
                return messageVO;
            }
            request.setAttribute("loginUser",userLoginLogPO);
        }catch (Exception e){
            throw new DataAccessException("【APP_登录注册模块_登录缓存用户】登录失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      游客登录
     * </desc>
     *
     * @param longitude 经度
     * @param latitude 纬度
     * @param uuid 设备ID
     * @param loginDevice 登录设备类型：1-android,2-iOS
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2020/04/30
     */
    @UnAuthAccessRequired
    @RequestMapping(path = "/touristLogin", method = RequestMethod.POST)
    @ResponseBody
    public Object touristLogin(String longitude, String latitude, String uuid, String loginDevice, String createTime, String sign, String language, HttpServletRequest request) {
        try {
            longitude = request.getAttribute("longitude") == null ? null : request.getAttribute("longitude").toString();
            latitude = request.getAttribute("latitude") == null ? null : request.getAttribute("latitude").toString();
            uuid = request.getAttribute("uuid") == null ? null : request.getAttribute("uuid").toString();
            loginDevice = request.getAttribute("loginDevice") == null ? null : request.getAttribute("loginDevice").toString();
            createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
            sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
            language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();

            //验签
            Map<String, String> params = new HashMap<>();
            params.put("longitude", longitude);
            params.put("latitude", latitude);
            params.put("uuid", uuid);
            params.put("loginDevice", loginDevice);
            params.put("createTime", createTime);
            params.put("language", language);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign, APP_REQUEST_PARAMS_ENCRYPT_KEY)) {
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language) ? AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode() : AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                return new MessageVO(errorCode);
            }
            if (StringUtils.isBlank(longitude) || StringUtils.isBlank(latitude) || StringUtils.isBlank(uuid) || StringUtils.isBlank(loginDevice)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            AppTouristDTO appTouristDTO = new AppTouristDTO();
            appTouristDTO.setPosition(longitude + "," + latitude);
            appTouristDTO.setUuid(uuid);
            appTouristDTO.setLoginDevice(loginDevice);
            appTouristDTO.setTokenKey(APP_USER_TOKEN_KEY);
            Map<String, Object> data = iAppRegisterServiceClient.touristLogin(appTouristDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);
        } catch (Exception e) {
            throw new DataAccessException("【APP_登录注册模块_游客登录缓存用户】游客登录失败",e);
        }
    }

    /**
     * <desc>
     *     APP端查询用户是否已登录
     * </desc>
     *
     * @return
     */
    @RequestMapping(path = "/appCheckIsLogin",method = RequestMethod.POST)
    @ResponseBody
    public Object appCheckIsLogin(String phoneNo,String loginDevice,String createTime,String sign,String uuid,String language,HttpServletRequest request){
        MessageVO messageVO;
        try {
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                phoneNo = request.getAttribute("phoneNo") == null ? null : request.getAttribute("phoneNo").toString();
                loginDevice = request.getAttribute("loginDevice") == null ? null : request.getAttribute("loginDevice").toString();
                uuid = request.getAttribute("uuid") == null ? null : request.getAttribute("uuid").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("phoneNo",phoneNo);
            params.put("createTime",createTime);
            params.put("loginDevice",loginDevice);
            params.put("uuid",uuid);
            params.put("language",language);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            } else {
                if (!Md5EncryptUtil.checkAppSignValue(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return  new MessageVO(errorCode);
                }
            }
            boolean isExistLogin = false;
            AppUserInfoPO appUserInfoPO;
            AppUserCacheVO oldCacheUserVO;
            if(LanguageTypeEnum.CHINESE.getLanguage().equals(language)){  //手机
                appUserInfoPO = iAppRegisterServiceClient.getUserByPhoneNo(phoneNo);
            }else {
                appUserInfoPO = iAppRegisterServiceClient.getUserByEmail(phoneNo);
            }
            if (appUserInfoPO != null){
                oldCacheUserVO = redisService.getObject(RedisConstant.APP_LOGIN+appUserInfoPO.getUserId(),AppUserCacheVO.class);
                if (oldCacheUserVO != null&&StringUtils.isNotBlank(oldCacheUserVO.getUuid())&&!uuid.equals(oldCacheUserVO.getUuid())){ //缓存存在，缓存中UUID与请求的UUID不一致
                    isExistLogin = true;
                }
            }
            ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.SUCCESS.getErrorCode():BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
            messageVO = new MessageVO(errorCode,isExistLogin);
        }catch (Exception e){
            throw new DataAccessException("【APP_登录注册模块_查询用户是否已登录】查询失败",e);
        }
        return messageVO;
    }


}
